#include "weatherre.h"
#include "ui_weatherre.h"

weatherRE::weatherRE(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::weatherRE)
{

    //初始背景

    QPalette pal (this->palette());
    QPixmap pix;
    pix.load(":/new/prefix1/image/UI3.jpg");
    pal.setBrush(backgroundRole(),QBrush(pix));
    this->setPalette(pal);

    //读取citykeys
    QString strLine;
    QStringList listLine;
    QFile cityfile("./cityKeys.txt");
    cityfile.open(QIODevice::ReadOnly);
    while(!cityfile.atEnd())
    {
        strLine=cityfile.readLine();
        strLine.remove("\n").remove(" ").remove("\r");
        listLine=strLine.split(":");
        this->cityKeys[listLine.at(1)]=listLine.at(0);
    }
    cityfile.close();

    //
     ui->setupUi(this);

     this->selectBG=0;
     ui->softb->hide();
     ui->rolllab->set_rollstr("欢迎来到天气查询平台");
    this->setEvetFilter();
    this->lable_init();
    QObject::connect(ui->softb,SIGNAL(send_cn(QString)),
                     this,SLOT(line_setText(QString)));
    QObject::connect(&manager,SIGNAL(finished(QNetworkReply*)),this,
                     SLOT(read_json(QNetworkReply*)));
}

weatherRE::~weatherRE()
{
    delete ui;
}

void weatherRE::on_lineEdit_textChanged(const QString &arg1)
{
   // qDebug()<<ui->lineEdit->hasFocus();
         if(ui->lineEdit->hasFocus())
         {
             this->newlength=ui->lineEdit->text().length();
             if(newlength<=0)
             {
                 QKeyEvent key(QKeyEvent::KeyPress,Qt::Key_Tab,Qt::NoModifier);
                  QApplication::sendEvent(ui->lineEdit,&key);
                 return;}
             if(newlength<lastlength)
             {
                 if(ui->lineEdit->text().isEmpty())
                 {
                     QKeyEvent key(QKeyEvent::KeyPress,Qt::Key_Tab,Qt::NoModifier);
                      QApplication::sendEvent(ui->lineEdit,&key);
                 }
             }
             if(newlength>lastlength)
             {
                             QString text=ui->lineEdit->text();
                            // qDebug()<<"1:"<<text;
                             text=text.remove(text.length()-1,text.length());
                             //qDebug()<<"2:"<<text;
                             ui->lineEdit->setText(text);

                             QKeyEvent key(QKeyEvent::KeyPress,Qt::Key_Tab,Qt::NoModifier);
                             QApplication::sendEvent(ui->lineEdit,&key);
             }
         }
         lastlength=ui->lineEdit->text().length();
        // qDebug()<<lastlength;
}
void weatherRE::line_setText(QString str)
{
    ui->lineEdit->setText(ui->lineEdit->text()
                          .append(str));
}
bool weatherRE::eventFilter(QObject *watched, QEvent *event)
{

        if(event->type()==QEvent::MouseButtonPress)
        {
            if(watched==ui->lineEdit)
            {
            ui->softb->show();
            if(ui->lineEdit->text().isEmpty())
            {
               ui->lineEdit->clearFocus();
               QKeyEvent key(QKeyEvent::KeyPress,Qt::Key_Tab,Qt::NoModifier);
               QApplication::sendEvent(ui->lineEdit,&key);
            }
            }
        }

        if(event->type()==QEvent::MouseButtonPress)
        {
            if(watched == ui->labbar||
                    watched==ui->cityname||watched==ui->today||watched==ui->rolllab
                    ||watched==ui->day1
                    ||watched==ui->gaomao)
            {
                ui->softb->hide();
            }

        }

}

void weatherRE::setEvetFilter()
{
    ui->day1->installEventFilter(this);
    ui->lineEdit->installEventFilter(this);
    ui->gaomao->installEventFilter(this);
    ui->labbar->installEventFilter(this);
    ui->cityname->installEventFilter(this);
    ui->today->installEventFilter(this);

    ui->rolllab->installEventFilter(this);
}

void weatherRE::on_pushButton_clicked()
{
    ui->softb->hide();
    QString cKey=ui->lineEdit->text();
    if(cKey.isEmpty())
    {
        qDebug()<<"1";
         qDebug()<<"2";
        return;
    }
    //发送请求url
    QString str_url("http://wthrcdn.etouch.cn/weather_mini?citykey=");
    str_url.append(cityKeys[cKey]);
    qDebug()<<str_url;

    QUrl url(str_url);
    QNetworkRequest request(url);
    this->manager.get(request);

}
void weatherRE::read_json(QNetworkReply *replay)
{
    QString json=replay->readAll();
    qDebug()<<json;
    this->paresingJson(json);
}
void weatherRE::paresingJson(QString json)
{
    QJsonParseError err;
    QJsonDocument doc=QJsonDocument::fromJson(json.toUtf8(),&err);
    if(err.error!=QJsonParseError::NoError)
    {
        qDebug()<<"格式错误";
        return;
    }

    QJsonObject root=doc.object();
    QJsonObject data=root.value("data").toObject();

    ui->cityname->setText(data.value("city").toString());
    ui->gaomao->setText(QString("感冒系数：")
                                        .append(data.value("ganmao").toString()));
    ui->nowtmp->setText(data.value("wendu").toString().append("℃"));

    //
    QJsonArray array=data.value("forecast").toArray();
    for(int i=0;i<array.count();i++)
    {
        date[i]->setText(array.at(i).toObject().value("date").toString());
        forcasttype[i]->setText(array.at(i).toObject().value("type").toString());
        //
        QString fengxiang=array.at(i).toObject().value("fengxiang").toString();
        QString fengli=array.at(i).toObject().value("fengli").toString();
        QString tmp;
        for(int j=0;j<fengli.length();j++)
        {
            if(fengli[j]>'0'&&fengli[j]<'9')
            {
                tmp.append(fengli[j]);
            }
        }
        feng[i]->setText(fengxiang.append(" ").append(tmp).append("级"));
        //
        QString low=array.at(i).toObject().value("low").toString();
        QString high=array.at(i).toObject().value("high").toString();
        low.remove("低温 ");
        high.remove("高温 ");
        temperature[i]->setText(low.append("~").append(high));
    }
    this->chang_weatherImg();
    QDateTime nowdate=QDateTime::currentDateTime();
    QString todate=nowdate.toString("yyyy年MM月dd日 ddd");
    ui->day1->setText(todate);
}

void weatherRE::lable_init()
{
    this->forcasttype[0]=ui->type1;     this->forcasttype[1]=ui->type2;
    this->forcasttype[2]=ui->type3;     this->forcasttype[3]=ui->type4;
    this->forcasttype[4]=ui->type5;

    this->date[0]=ui->day1;     this->date[1]=ui->day2;
    this->date[2]=ui->day3;     this->date[3]=ui->day4;
    this->date[4]=ui->day5;

    this->temperature[0]=ui->temperature1;      this->temperature[1]=ui->temperature2;
    this->temperature[2]=ui->temperature3;      this->temperature[3]=ui->temperatrue4;
    this->temperature[4]=ui->temperature5;

    this->feng[0]=ui->feng1;        this->feng[1]=ui->feng2;
    this->feng[2]=ui->feng3;        this->feng[3]=ui->feng4;
    this->feng[4]=ui->feng5;

    this->img[0]=ui->imgday1;      this->img[1]=ui->imgday2;
    this->img[2]=ui->imgday3;       this->img[3]=ui->imgday4;
    this->img[4]=ui->imgday5;

}

void weatherRE::chang_weatherImg()
{
    for(int i=0;i<5;i++)
    {
        this->img[i]->setStyleSheet("");
        this->img[i]->clear();
        QPixmap pic;
        pic.load(QString(":/new/prefix1/image/")
                        .append(forcasttype[i]->text()).append(".png"));
        pic=pic.scaled(this->img[i]->size(),
                                    Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        this->img[i]->setPixmap(pic);
    }
}

void weatherRE::darw_block()
{
    QPainter painter(this);
    painter.fillRect(270,130,20,350,Qt::white);
}


void weatherRE::on_closeBt_clicked()
{
    this->close();
}

void weatherRE::on_hideBt_clicked()
{
    this->setWindowState(Qt::WindowMinimized);
}

void weatherRE::on_changPicBt_clicked()
{
    if(selectBG>5)
    {
        selectBG=0;
    }

    qDebug()<<"1";
    QPalette pal (this->palette());
    QPixmap pix;
    pix.load(QString(":/new/prefix1/image/").append("UI")
                    .append(QString::number(selectBG)).append(".png"));
    pal.setBrush(backgroundRole(),QBrush(pix));
    this->setPalette(pal);
    qDebug()<<"2";
    selectBG++;
       qDebug()<<"3";
}
